"""
Case Type   : portal执行流程优化（一）
Case Name   : 离线安装portal
Create At   : 2025/9/16
Owner       : lonely-dance
Description :
    1、导入服务器
    2、安装迁移工具
    3、清理环境
Expect      :
    1、导入成功
    2、成功
    3、清理环境成功
History     :
"""

import os
import re
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from testcase.utils.datakit_api.CommonApi import CommonApi
from testcase.utils.datakit_api.DataMigration import DataMigrationApi
from testcase.utils.CommonDatakit import CommonDatakit
from testcase.utils.CommonMySQL import CommonMySQL


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.mysql_node = Node('mysql5')
        self.mysql_root_node = Node('mysql5Root')
        self.primary_node = Node('PrimaryDbUser')
        self.primary_root_node = Node('PrimaryRoot')
        self.datakit_node = Node('Datakit')
        self.host_list = [self.datakit_node]
        self.com_sh = CommonSH('PrimaryDbUser')
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotEqual("error", self.token)
        self.com_api = CommonApi(self.token)
        self.datakit_sh = CommonDatakit(self.token)
        self.com_mysql = CommonMySQL('mysql5')
        self.data_migration_api = DataMigrationApi(self.token)
        self.og_host_id = ''
        self.portal_pkg_url = ''

    def test_migration_datakit(self):
        text = '----step1:添加服务器及实例 expect:成功----'
        self.log.info(text)
        self.datakit_sh.import_host(self.host_list)

        res = self.com_api.get_host_page(name=self.datakit_node.db_host)
        self.log.info(res.json())
        self.og_host_id = res.json()['rows'][0]['hostId']
        res = self.com_api.get_hostUser_page(self.og_host_id)
        self.log.info(res.json())
        og_host_user_id = ''
        for item in res.json()['rows']:
            if item['username'] == self.datakit_node.ssh_user:
                og_host_user_id = item['hostUserId']

        text = '----step2:本地下载portal安装包 expect:成功----'
        self.log.info(text)
        response = self.data_migration_api.post_plugins_data_migration_resource_getHosts()
        self.log.info(response.json())
        os_type = response.json()['data']['records'][0]['hostInfo']['os'] + response.json()['data']['records'][0]['hostInfo']['osVersion']
        cpu_arch = response.json()['data']['records'][0]['hostInfo']['cpuArch']
        self.portal_pkg_url = f'{macro.FTP_PATH}/tools/{os_type}/PortalControl-{macro.DATAKIT_VERSION}-{cpu_arch}.tar.gz'
        cmd = f'cd {macro.DATAKIT_INSTALL_PATH};wget {self.portal_pkg_url};'
        res = self.datakit_node.sh(cmd).result()
        self.assertIn('100%', res, '安装包下载失败')

        text = '----step2:安装迁移工具 expect:成功----'
        self.log.info(text)
        data = {
            'runHostId': self.og_host_id,
            'installPath': macro.DATAKIT_INSTALL_PATH,
            'hostUserId': og_host_user_id,
            'installType': 1,
            'pkgDownloadUrl': None,
            'jarName': 'portalControl-1.0-SNAPSHOT-exec.jar',
            'portalVersion': 'EXPERIMENTAL',
            'thirdPartySoftwareConfig.thirdPartySoftwareConfigType': 2,
            'thirdPartySoftwareConfig.zookeeperPort': 12181,
            'thirdPartySoftwareConfig.kafkaPort': 19092,
            'thirdPartySoftwareConfig.installDir': f'{macro.DATAKIT_INSTALL_PATH}/portal/tools/debezium/',
            'thirdPartySoftwareConfig.schemaRegistryPort': 18081,
            'portalType': 'MYSQL_ONLY',
            'pkgName': os.path.basename(self.portal_pkg_url),
            'pkgUploadPath': {}
        }
        response = self.data_migration_api.post_plugins_data_migration_resource_installPortal(host_id=self.og_host_id,
                                                                                              data=data,
                                                                                              ssh_host=self.datakit_node.ssh_host,
                                                                                              ssh_username=self.datakit_node.ssh_user,
                                                                                              ssh_password=self.datakit_node.ssh_password,
                                                                                              files_path=os.path.join(macro.DATAKIT_INSTALL_PATH, os.path.basename(self.portal_pkg_url)))
        self.log.info(response.json())
        self.assertEqual(200, response.json()['code'], '执行失败:' + text)

        i = 0
        while True:
            time.sleep(60)
            response = self.data_migration_api.post_plugins_data_migration_resource_getHosts()
            self.log.info(response.json())
            i += 1
            if response.json()['data']['records'][0]['installInfo']['installStatus'] == 2:
                self.log.info('----portal安装成功----')
                break
            self.assertNotEqual(3, response.json()['data']['records'][0]['installInfo']['installStatus'],
                                'portal安装失败')
            if i > 10:
                self.assertEqual(2, response.json()['data']['records'][0]['installInfo']['installStatus'],
                                 'portal安装失败')
                break

    def tearDown(self):
        text = f'----step3:清理环境 expect:成功----'
        self.log.info(text)
        cmd = f'cd {macro.PORTAL_INSTALL_PATH};rm -rf {os.path.basename(self.portal_pkg_url)};'
        self.log.info(cmd)
        self.datakit_node.sh(cmd)
        response2 = self.data_migration_api.delete_plugins_data_migration_resource_deletePortal(self.og_host_id)
        self.log.info(response2.json())

        self.datakit_sh.delete_db()
        self.datakit_sh.delete_host()

        self.assertEqual(200, response2.json()['code'], '卸载portal失败')
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
